<?php 
/**
* 默认类
*/
class UserController extends Controller
{
	
	public function reg()
	{
	 	$this->display();
	}

	public function Login()
	{
	 	$this->display();
	}

	public function LoginOut()
	{
		session_unset();
		session_destroy();
		header("Location:./index.php");
	}

	public function Checklogin()
	{
		$data = $_POST;

		$user = db('user')->where(['nickname'=>$data['nickname'],'password'=>md5($data['password'])])->findOne();

		if($user){

			$_SESSION['nickname']= $user[0]['nickname'];
			$_SESSION['uid']= $user[0]['uid'];
			header("Location:./index.php");
		}else{
			header("Location:./index.php?m=index&c=user&a=login");
		}

	}

	public function add()
	{
		$data = $_POST;
		$data['ctime'] = time();
		unset($data['repassword']);
		$data['password'] = md5($data['password']);
		$db = db('user');
		$db->add($data);
		header("Location:./index.php?m=index&c=user&a=login");
	}

	public function checkdata()
	{
		switch ($_POST['name']) {
			case 'nickname':
				$this->checkUsername();
				break;
			case 'email':
				$this->checkEmail();
				break;
			case 'phone':
				$this->checkPhone();
				break;
			default:
				# code...
				break;
		}
	}

	public function checkUsername()
	{
		$nickname = $_POST['data'];

		$preg = "/^[a-z][a-z0-9]{5,7}$/i";

		$c = preg_match($preg, $nickname);

		if(!$c){
			echo json_encode(['error'=>1,'info'=>'用户名不符合要求，6-8位']);exit;
		}

		$user = db('user')->where(['nickname'=>$nickname])->findOne();

		if($user){
			echo json_encode(['error'=>1,'info'=>'用户名已存在']);
				exit;
		}

		echo json_encode(['error'=>0,'info'=>'用户名可用']);
				exit;
	}

	public function checkEmail()
	{
		$email = $_POST['data'];

		$preg = "/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/";

		$c = preg_match($preg, $email);

		if(!$c){
			echo json_encode(['error'=>1,'info'=>'邮箱格式不对']);exit;
		}

		$user = db('user')->where(['email'=>$email])->findOne();

		if($user){
			echo json_encode(['error'=>1,'info'=>'邮箱已存在']);
				exit;
		}

		echo json_encode(['error'=>0,'info'=>'可用']);
				exit;
	}

	public function checkPhone()
	{
		$phone = $_POST['data'];

		$preg = "/^1[3|4|5|8][0-9]\d{4,8}$/";

		$c = preg_match($preg, $phone);

		if(!$c){
			echo json_encode(['error'=>1,'info'=>'手机格式不对']);exit;
		}

		
		$user = db('user')->where(['phone'=>$phone])->findOne();

		if($user){
			echo json_encode(['error'=>1,'info'=>'手机已存在']);
				exit;
		}

		echo json_encode(['error'=>0,'info'=>'可用']);
				exit;
	}


}

 ?>